package com.itcv.redis.controller;

import com.itcv.redis.basic.PatientInfo;
import com.itcv.redis.query.PatientQuery;
import com.itcv.redis.service.PatientInfoService;
import com.itcv.redis.util.GenerateNameUtil;
import com.itcv.redis.util.IdCardGeneratorUtil;
import com.itcv.redis.util.PrimaryKeyUtil;
import com.itcv.redis.util.RedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.concurrent.CountDownLatch;

@RestController
public class PatientController {

    private static Logger logger = LoggerFactory.getLogger(PatientController.class);

    @Autowired
    private PatientInfoService patientInfoService;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private PrimaryKeyUtil primaryKeyUtil;

    private static  int num = 5;

    private static String productCode = "Y100085";

    @RequestMapping("/query")
    public void queryPatientList(){
        try {
            PatientQuery patientQuery = new PatientQuery();
            patientQuery.setPatientName("李明");
            patientInfoService.selectPatientList(patientQuery);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/test")
    public void redisLockTest (){
        CountDownLatch countDownLatch = new CountDownLatch(1);

        for (int i = 0; i <5 ; i++) {
            //  reduceStorage();
            Thread threadA = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        System.out.println("测试数据！！！");
                        countDownLatch.await();
                        reduceStorage();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
            threadA.start();
        }
        countDownLatch.countDown();
        System.out.println("库存剩余为"+num);

    }

    public void reduceStorage(){
        try {
            System.out.println("线程"+Thread.currentThread().getName()+"开始获得锁");
            boolean redisLock = redisUtil.tryLock(productCode,"1",1L,15L);
            System.out.println("redisLock = "+redisLock);
            if(redisLock){
                System.out.println("线程"+Thread.currentThread().getName()+"获得锁");
                Thread.sleep(2000);//处理业务时长
                num = num -1;
                System.out.println("当前库存为"+num);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.out.println("线程"+Thread.currentThread().getName()+"释放锁");
            redisUtil.unLock(productCode);
        }

    }

    @RequestMapping(value = "/matchDb")
    public void matchDb(){
        List<PatientInfo> patientInfoList = new ArrayList<>();
        for(int i=0;i<10000;i++){
            try {
                PatientInfo patientInfo = new PatientInfo();
                patientInfo.setIdentificationNum(IdCardGeneratorUtil.generate());
                patientInfo.setPatientName(GenerateNameUtil.generateName());
                String identificationNum = patientInfo.getIdentificationNum();
                if(identificationNum.length()>14){
                    String bornStr = identificationNum.substring(6,14);
                    DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
                    Date date = dateFormat.parse(bornStr);
                    patientInfo.setBornDate(date);
                }else{
                    logger.info("记录一下这个身份证号{}"+identificationNum);
                    continue;
                }

                Random random = new Random();
                Byte b = Byte.valueOf(String.valueOf(random.nextInt(2)+1));
                patientInfo.setPatientSex(b);
                String prefix = primaryKeyUtil.getOrderIdPrefix(new Date());
                String globaleId = prefix+primaryKeyUtil.orderId(prefix);
                patientInfo.setGlobalId(globaleId);
                patientInfoList.add(patientInfo);
                num++;
            } catch (ParseException e) {
                e.printStackTrace();
                logger.error("初始化数据执行异常",e);
            }
        }
        patientInfoService.matchByDb(patientInfoList);
    }


}
